import { UserProfile } from '../../auth/types';
import { API_PATHS, API_BASE_URL, getAuthHeaders } from '../../../config/apiConfig';

const API_BASE = API_PATHS.resources;

export interface Resource {
  id: string;
  title: string;
  description: string;
  coverUrl: string;
  coverImageUrl?: string; // 后端返回的封面图URL
  uploaderId: string;
  uploaderName: string;
  createdAt: string;
  updatedAt: string;
  size: number;
  downloadCount: number;
  torrentId: string;
  reviewStatus?: 'WAIT' | 'PASS' | 'REFUSE';
  rejectReason?: string;
  points?: number; // 资源所需积分
}

export interface ResourceListResponse {
  total: number;
  records: Resource[];
  page?: number;
  pageSize?: number;
}

export class ResourceService {
  private static getHeaders(includeAuth: boolean = true) {
    const headers: Record<string, string> = {
      'Accept': 'application/json',
      'Content-Type': 'application/json',
    };

    if (includeAuth) {
      const token = localStorage.getItem('token');
      if (token) {
        headers['Authorization'] = `Bearer ${token}`;
      }
    }

    return headers;
  }

  static async saveResource(resource: Partial<Resource>): Promise<Resource> {
    const response = await fetch(`${API_BASE}/upload`, {
      method: 'POST',
      headers: this.getHeaders(),
      body: JSON.stringify(resource)
    });

    if (!response.ok) {
      const error = await response.json();
      throw new Error(error.message || '保存资源失败');
    }

    return response.json();
  }

  static async getResourceById(id: string): Promise<Resource> {
    const response = await fetch(`${API_BASE}/${id}`, {
      method: 'GET',
      headers: this.getHeaders()
    });

    if (!response.ok) {
      const error = await response.json();
      throw new Error(error.message || '获取资源详情失败');
    }

    return response.json();
  }

  static async queryResources(query: string): Promise<ResourceListResponse> {
    const response = await fetch(`${API_BASE}/getList?keyword=${encodeURIComponent(query)}`, {
      method: 'GET',
      headers: this.getHeaders()
    });

    if (!response.ok) {
      const error = await response.json();
      throw new Error(error.message || '查询资源失败');
    }

    return response.json();
  }

  static async searchResources(params: { id?: string; title?: string; uploader?: string }): Promise<ResourceListResponse> {
    // 构建查询参数
    const queryParams = new URLSearchParams();
    if (params.id) queryParams.append('id', params.id);
    if (params.title) queryParams.append('title', params.title);
    if (params.uploader) queryParams.append('uploader', params.uploader);
    
    const response = await fetch(`${API_BASE}/search?${queryParams.toString()}`, {
      method: 'GET',
      headers: this.getHeaders()
    });

    if (!response.ok) {
      const error = await response.json();
      throw new Error(error.message || '搜索资源失败');
    }

    return response.json();
  }

  static async getResourceList(page: number = 1, pageSize: number = 10): Promise<ResourceListResponse> {
    const response = await fetch(`${API_BASE}/getList?page=${page}&size=${pageSize}`, {
      method: 'GET',
      headers: this.getHeaders()
    });

    if (!response.ok) {
      const error = await response.json();
      throw new Error(error.message || '获取资源列表失败');
    }

    const data = await response.json();
    console.log('获取资源列表响应数据:', data);
    return data;
  }

  static async getResourcesByStatus(page: number = 1, size: number = 10, status: string = ''): Promise<ResourceListResponse> {
    // 如果是筛选特定状态的资源，则使用对应的API
    if (status) {
      let url;
      if (status === 'WAIT') {
        // 使用/pending接口获取待审核资源
        url = `${API_BASE}/pending?page=${page}&size=${size}`;
        
        const response = await fetch(url, {
          method: 'GET',
          headers: this.getHeaders()
        });

        if (!response.ok) {
          const error = await response.json();
          throw new Error(error.message || '获取资源列表失败');
        }

        // 获取响应数据
        const data = await response.json();
        
        // 确保待审核资源的reviewStatus字段被设置为'WAIT'
        const records = data.records.map((resource: Resource) => ({
          ...resource,
          reviewStatus: 'WAIT'
        }));
        
        return {
          ...data,
          records
        };
      } else {
        // 使用/getList接口获取已审核资源（通过或拒绝）
        url = `${API_BASE}/getList?page=${page}&size=${size}&status=${status}`;
        
        const response = await fetch(url, {
          method: 'GET',
          headers: this.getHeaders()
        });

        if (!response.ok) {
          const error = await response.json();
          throw new Error(error.message || '获取资源列表失败');
        }

        // 获取响应数据
        const data = await response.json();
        
        // 确保已审核资源的reviewStatus字段被正确设置，并过滤出指定状态的资源
        const records = data.records
          .map((resource: Resource) => ({
            ...resource,
            reviewStatus: resource.reviewStatus || status // 使用传入的status参数设置reviewStatus
          }))
          .filter((resource: Resource) => resource.reviewStatus === status); // 只保留指定状态的资源
        
        return {
          ...data,
          records,
          total: records.length // 更新总数为过滤后的数量
        };
      }
    } else {
      // 获取所有状态的资源（包括待审核、已通过、已拒绝）
      // 先获取待审核资源
      const pendingResponse = await fetch(`${API_BASE}/pending?page=${page}&size=${size}`, {
        method: 'GET',
        headers: this.getHeaders()
      });

      // 再获取已审核资源（通过和拒绝）
      const reviewedResponse = await fetch(`${API_BASE}/getList?page=${page}&size=${size}`, {
        method: 'GET',
        headers: this.getHeaders()
      });

      if (!pendingResponse.ok || !reviewedResponse.ok) {
        const error = pendingResponse.ok ? await reviewedResponse.json() : await pendingResponse.json();
        throw new Error(error.message || '获取资源列表失败');
      }

      const pendingData = await pendingResponse.json();
      const reviewedData = await reviewedResponse.json();

      // 确保待审核资源的reviewStatus字段被设置为'WAIT'
      const pendingRecords = pendingData.records.map((resource: Resource) => ({
        ...resource,
        reviewStatus: 'WAIT'
      }));

      // 确保已审核资源的reviewStatus字段被正确设置
      // 由于/getList接口没有指定status参数，可能会返回多种状态的资源
      // 我们需要确保每个资源都有正确的reviewStatus，并且只保留已通过的资源
      const reviewedRecords = reviewedData.records
        .map((resource: Resource) => ({
          ...resource,
          reviewStatus: resource.reviewStatus || 'PASS'
        }))
        .filter((resource: Resource) => resource.reviewStatus === 'PASS'); // 只保留已通过的资源

      // 合并两个列表的资源
      const combinedRecords = [...pendingRecords, ...reviewedRecords];
      const totalRecords = pendingData.total + reviewedRecords.length; // 使用过滤后的已审核资源数量

      // 返回合并后的结果
      return {
        total: totalRecords,
        records: combinedRecords,
        page: page,
        pageSize: size
      };
    }
  }

  static async deleteResource(id: string): Promise<void> {
    const response = await fetch(`${API_BASE}/${id}/delete`, {
      method: 'DELETE',
      headers: this.getHeaders()
    });

    if (!response.ok) {
      const error = await response.json();
      throw new Error(error.message || '删除资源失败');
    }
  }

  static async downloadResource(id: string): Promise<Blob> {
    const response = await fetch(`${API_BASE}/download/${id}`, {
      method: 'GET',
      headers: {
        ...this.getHeaders(),
        'Accept': 'application/octet-stream' // 明确请求二进制数据
      }
    });

    if (!response.ok) {
      const error = await response.json().catch(() => ({ message: '下载资源失败' }));
      throw new Error(error.message || '下载资源失败');
    }

    return response.blob(); // 返回blob数据
  }

  static async payPoints(id: string): Promise<void> {
    const response = await fetch(`${API_BASE}/payPoints/${id}`, {
      method: 'POST',
      headers: this.getHeaders()
    });

    if (!response.ok) {
      const error = await response.json();
      throw new Error(error.message || '积分支付失败');
    }
  }

  static async getRecommendedResources(page: number = 1, size: number = 10): Promise<ResourceListResponse> {
    const response = await fetch(`/api/resource/recommend?page=${page}&size=${size}`, {
      method: 'GET',
      headers: this.getHeaders()
    });

    if (!response.ok) {
      const error = await response.json();
      throw new Error(error.message || '获取推荐资源失败');
    }

    return response.json();
  }

  // 获取待审核资源详情
  static async getResourceForReview(id: string): Promise<Resource> {
    const response = await fetch(`${API_BASE}/review/${id}`, {
      method: 'GET',
      headers: this.getHeaders()
    });

    if (!response.ok) {
      const error = await response.json();
      throw new Error(error.message || '获取审核资源详情失败');
    }

    return response.json();
  }

  // 审核资源
  static async reviewResource(id: string, approve: boolean, reason: string = ''): Promise<void> {
    const response = await fetch(`${API_BASE}/review`, {
      method: 'PUT',
      headers: this.getHeaders(),
      body: JSON.stringify({
        id,
        approve,
        reason
      })
    });
    if (!response.ok) {
      const error = await response.json();
      throw new Error(error.message || '审核资源失败');
    }
  }

  // 获取用户购买的资源列表
  static async getPurchasedResources(page: number = 1, size: number = 10): Promise<ResourceListResponse> {
    const response = await fetch(`${API_BASE}/purchased?page=${page}&size=${size}`, {
      method: 'GET',
      headers: this.getHeaders()
    });

    if (!response.ok) {
      const error = await response.json();
      throw new Error(error.message || '获取购买资源列表失败');
    }

    return response.json();
  }

  // 获取用户自己发布的资源列表
  static async getMyResources(page: number = 1, size: number = 10): Promise<ResourceListResponse> {
    const response = await fetch(`${API_BASE}/my?page=${page}&size=${size}`, {
      method: 'GET',
      headers: this.getHeaders()
    });

    if (!response.ok) {
      const error = await response.json();
      throw new Error(error.message || '获取我的资源列表失败');
    }

    return response.json();
  }

  static async getTags(): Promise<any[]> {
    try {
      console.log('Fetching tags from API...');
      const response = await fetch(`${API_BASE_URL}/api/tag/tags`, {
        method: 'GET',
        headers: this.getHeaders()
      });

      if (!response.ok) {
        const error = await response.json();
        console.error('Failed to fetch tags:', error);
        throw new Error(error.message || '获取标签列表失败');
      }

      const data = await response.json();
      console.log('Tags fetched successfully:', data);
      return data;
    } catch (error) {
      console.error('Error fetching tags:', error);
      return [];
    }
  }

  static async getResourcesByTag(tagsId: string, page: number = 1, size: number = 10): Promise<ResourceListResponse> {
    try {
      console.log('Fetching resources by tag ID:', tagsId);
      
      // 使用GET请求，将tagsId作为查询参数传递，参数名改为tagId
      const params = new URLSearchParams({
        page: page.toString(),
        size: size.toString(),
        tagId: tagsId
      });
      
      const response = await fetch(`${API_BASE}/getList?${params}`, {
        method: 'GET',
        headers: this.getHeaders()
      });

      if (!response.ok) {
        const error = await response.json();
        console.error('Failed to fetch resources by tag:', error);
        throw new Error(error.message || '根据标签获取资源列表失败');
      }

      const data = await response.json();
      console.log('Resources fetched by tag successfully:', data);
      return data;
    } catch (error) {
      console.error('Error fetching resources by tag:', error);
      throw error;
    }
  }
}